#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include"commo.hpp"
const int gdefaultid = -1;
const int gsize = 4096;
const std::string pathname = ".";
const int projid = 0x66;
const int gmode = 0666;
#define CREATER "creater"
#define USER "user"

class Shm
{
private:
    // 创建的一定要是一个全新的共享内存
    void CreatHelp(int flag)
    {
         printf("key: 0x%x\n", _key);
        _id = shmget(_key, _size, flag);
        if (_id < 0)
        {
            ERR_EXIT("shmget");
        }
        printf("shmid: %d\n", _id);
    }
    void Creat()
    {
        CreatHelp(IPC_CREAT | IPC_EXCL | 0666);
    }
    void Get()
    {
        CreatHelp(IPC_CREAT);
    }
    void attach()
    {
        _address = shmat(_id, nullptr, 0);
        if ((long long)_address < 0)
        {
            ERR_EXIT("shmat");
        }
        printf("shmat successful\n");
    }
    void Destroy()
    {
        int n = shmctl(_id, IPC_RMID, nullptr);
        if (n < 0)
        {
            ERR_EXIT("shmctl");
        }
        printf("shmctl successful\n");
    }

public:
    Shm(const std::string &pathname, int projid, const std::string &usertype)
        : _id(gdefaultid), _size(gsize), _address(nullptr), _username(usertype)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok");
        }
        if (_username== CREATER)
            Creat();
        else if (_username== USER)
            Get();
        else
        {
        }
        attach();
    }

    void *RetAddress()
    {
        return _address;
    }
    int RetSize()
    {
        return _size;
    }
    ~Shm()
    {
        std::cout << _username << std::endl;
        if(_username == CREATER)
        Destroy();

    }

private:
    int _id;
    int _size;
    key_t _key;
    void *_address;
    std::string _username;
};